<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SKU编码" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="损耗原因" prop="lossReason">
        <el-select v-model="queryParams.lossReason" placeholder="请选择损耗原因" clearable>
          <el-option label="海外丢失" value="海外丢失" />
          <el-option label="破损" value="破损" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属店铺" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopName"
            :value="item.shopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="损耗日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['stock:loss:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stock:loss:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['stock:loss:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['stock:loss:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="lossList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU编码" align="center" prop="sku" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productName" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="SKU属性" align="center" prop="skuAttr" width="110" :show-overflow-tooltip="true" />
      <el-table-column label="损耗数量" align="center" prop="lossQuantity" width="100">
        <template slot-scope="scope">
          <span style="color: #F56C6C; font-weight: bold;">{{ scope.row.lossQuantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="损耗原因" align="center" prop="lossReason" width="100" />
      <el-table-column label="损耗日期" align="center" prop="lossDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lossDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属店铺" align="center" prop="shopName" width="110" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['stock:loss:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['stock:loss:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU编码" prop="sku">
              <el-select 
                v-model="form.sku" 
                placeholder="请选择库存中的SKU" 
                filterable 
                style="width: 100%" 
                :disabled="form.lossId != null"
                @change="handleSkuChange"
              >
                <el-option
                  v-for="item in stockDetailOptions"
                  :key="item.sku"
                  :label="item.sku + ' - ' + item.productName + ' (库存' + item.remainingStock + '个)'"
                  :value="item.sku"
                >
                  <span style="float: left">{{ item.sku }} - {{ item.productName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">库存{{ item.remainingStock }}个</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="选择SKU后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU属性" prop="skuAttr">
              <el-input v-model="form.skuAttr" placeholder="选择SKU后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属店铺" prop="shopId">
              <el-select v-model="form.shopId" placeholder="选择SKU后自动填充" style="width: 100%" disabled>
                <el-option
                  v-for="item in shopOptions"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="损耗数量" prop="lossQuantity">
              <el-input-number v-model="form.lossQuantity" :min="1" :max="form.currentStock || 999999" placeholder="请输入损耗数量" style="width: 100%" />
              <span v-if="form.currentStock" style="color: #909399; font-size: 12px; margin-left: 10px;">
                （当前库存：{{ form.currentStock }}个）
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="损耗原因" prop="lossReason">
              <el-select v-model="form.lossReason" placeholder="请选择损耗原因" style="width: 100%">
                <el-option label="海外丢失" value="海外丢失" />
                <el-option label="破损" value="破损" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="损耗日期" prop="lossDate">
              <el-date-picker
                v-model="form.lossDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择损耗日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStockLoss, getStockLoss, delStockLoss, addStockLoss, updateStockLoss } from "@/api/business/stockLoss"
import { getStockDetail } from "@/api/business/stock"
import { getShopList } from "@/api/system/user"

export default {
  name: "StockLoss",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存损耗表格数据
      lossList: [],
      // 店铺选项
      shopOptions: [],
      // 库存明细选项（有库存的SKU）
      stockDetailOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        productName: null,
        lossReason: null,
        shopId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sku: [
          { required: true, message: "SKU编码不能为空", trigger: "blur" }
        ],
        lossQuantity: [
          { required: true, message: "损耗数量不能为空", trigger: "blur" }
        ],
        lossReason: [
          { required: true, message: "损耗原因不能为空", trigger: "change" }
        ],
        lossDate: [
          { required: true, message: "损耗日期不能为空", trigger: "blur" }
        ],
        shopId: [
          { required: true, message: "所属店铺不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
    this.getStockDetailOptions()
  },
  methods: {
    /** 查询库存损耗列表 */
    getList() {
      this.loading = true
      listStockLoss(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.lossList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    /** 获取库存明细选项（只显示有库存的SKU） */
    getStockDetailOptions() {
      getStockDetail({ pageNum: 1, pageSize: 10000 }).then(response => {
        // 过滤掉剩余库存为0的记录
        this.stockDetailOptions = response.rows.filter(item => item.remainingStock > 0)
      })
    },
    /** SKU改变时自动填充产品名称、SKU属性、店铺和当前库存 */
    handleSkuChange(sku) {
      const stockDetail = this.stockDetailOptions.find(s => s.sku === sku)
      if (stockDetail) {
        this.form.productName = stockDetail.productName
        this.form.skuAttr = stockDetail.skuAttr
        this.form.shopId = stockDetail.shopId
        this.form.currentStock = stockDetail.remainingStock
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        lossId: null,
        sku: null,
        productName: null,
        skuAttr: null,
        lossQuantity: null,
        lossReason: null,
        lossDate: null,
        shopId: null,
        remark: null,
        currentStock: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lossId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 重新获取最新的库存明细数据
      this.getStockDetailOptions()
      this.open = true
      this.title = "添加库存损耗"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const lossId = row.lossId || this.ids
      getStockLoss(lossId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改库存损耗"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lossId != null) {
            updateStockLoss(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStockLoss(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lossIds = row.lossId || this.ids
      this.$modal.confirm('是否确认删除库存损耗编号为"' + lossIds + '"的数据项？').then(function() {
        return delStockLoss(lossIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/stock/loss/export', {
        ...this.queryParams
      }, `库存损耗_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 只读字段样式 */
.el-input.is-disabled .el-input__inner,
.el-input__inner[readonly] {
  background-color: #f5f7fa;
  color: #606266;
  cursor: not-allowed;
}
</style>

